package com.agent.membership.controller.app;

import com.agent.common.result.ApiResponse;
import com.agent.common.utils.UserInfoUtils;
import com.agent.membership.dto.CreditOptions;
import com.agent.membership.entity.CreditAccount;
import com.agent.membership.service.CreditService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 积分控制器
 * @author Jeff_Wan
 * @description 提供会员相关的API接口
 */
@RestController
@RequestMapping("/credits")
@RequiredArgsConstructor
public class CreditController {
    private final CreditService creditService;

    /**
     * 获取用户积分详情
     *
     * @return 积分账户信息
     */
    @GetMapping("/account/info")
    public ApiResponse<CreditAccount> getCreditAccount() {
        return ApiResponse.success(creditService.getCreditAccount(UserInfoUtils.getUserId()));
    }

    /**
     * 计算任务所需积分
     * @param options 任务参数
     * @return 所需积分数量
     */
    @PostMapping("/calculate")
    public ApiResponse<Integer> calculateRequiredCredits(@RequestBody @Valid CreditOptions options) {
        return ApiResponse.success(creditService.calculateRequiredCredits(options));
    }

    /**
     * 扣除积分
     *
     * @param amount 积分数量
     * @param source 来源描述
     * @param relatedId 关联ID
     * @return 是否成功
     */
    @PostMapping("/deduct")
    public ApiResponse<Boolean> deductCredits(
            @RequestParam("amount") Integer amount,
            @RequestParam("source") String source,
            @RequestParam(name = "relatedId", required = false) Long relatedId) {
        boolean success = creditService.deductCredits(UserInfoUtils.getUserId(), amount, source, relatedId);
        return ApiResponse.success(success);
    }
}